package cc.pptshow.ppt.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextParagraph;
import org.apache.poi.xslf.usermodel.XSLFTextRun;
import org.apache.poi.xslf.usermodel.XSLFTextShape;
import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTextFont;

public class PPT2ImgUtil {

    public static void main(String[] args) {
        File ppt = new File("C:\\Users\\qrp19\\Desktop\\1654704829734.pptx");
        String img = "C:\\Users\\qrp19\\Desktop\\demo";
        System.out.println(converPPTtoImage(ppt,img,"png",3));
    }


    public static int converPPTtoImage(File orignalPPTFile,String targetImageFileDir,
                                       String imageFormatNameString, int times) {

        //验证图片是否为pptx格式
        if(!checkIsPPTFile(orignalPPTFile)){
            System.out.print("转换文件必须是pptx!");
            return 0;
        }
        List<String> list = new ArrayList<String>();
        FileInputStream is = null ;
        int imgCount = 0;
        File imgFile = new File(targetImageFileDir);
        //如果没有文件夹就创建文件夹
        createDirIfNotExist(targetImageFileDir);
        try {
            is = new FileInputStream(orignalPPTFile);
            XMLSlideShow xmlSlideShow = new XMLSlideShow(is);
            is.close();
            // 获取大小
            Dimension pgsize = xmlSlideShow.getPageSize();
            // 获取幻灯片
            XSLFSlide[] slides = xmlSlideShow.getSlides().toArray(new XSLFSlide[0]);
            imgCount = slides.length;
            for (int i = 0 ; i < slides.length ; i++) {
                // 解决乱码问题
                XSLFShape[] shapes = slides[i].getShapes().toArray(new XSLFShape[0]);
                for (XSLFShape shape : shapes) {
                    if (shape instanceof XSLFTextShape) {
                        XSLFTextShape sh = (XSLFTextShape) shape;
                        List<XSLFTextParagraph> textParagraphs = sh.getTextParagraphs();
                        for (XSLFTextParagraph xslfTextParagraph : textParagraphs) {
                            List<XSLFTextRun> textRuns = xslfTextParagraph.getTextRuns();
                            for (XSLFTextRun xslfTextRun : textRuns) {
                                xslfTextRun.setFontFamily("字体圈欣意冠黑体");
                                CTRegularTextRun xmlObject = (CTRegularTextRun) xslfTextRun.getXmlObject();
                                CTTextCharacterProperties rPr = xmlObject.getRPr();
                                CTTextFont ctTextFont = rPr.addNewEa();
                                ctTextFont.setTypeface("字体圈欣意冠黑体");
                            }
                        }
                    }
                }
                // 创建BufferedImage对象，图像的尺寸为原来的每页的尺寸*倍数times
                BufferedImage img = new BufferedImage(pgsize.width * times,
                        pgsize.height * times, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.scale(times, times);// 将图片放大times倍
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width,pgsize.height));
                // 最核心的代码
                slides[i].draw(graphics);
                //图片将要存放的路径
                String absolutePath = imgFile.getAbsolutePath()+"/"+ (i + 1) + "." + imageFormatNameString;
                File jpegFile = new File(absolutePath);
                // 图片路径存放
                list.add((i + 1) + ".jpg");
                //如果图片存在，则不再生成
                if (jpegFile.exists()) {
                    continue;
                }
                // 这里设置图片的存放路径和图片的格式(jpeg,png,bmp等等),注意生成文件路径
                FileOutputStream out = new FileOutputStream(jpegFile);
                // 写入到图片中去
                ImageIO.write(img, "jpeg", out);
                out.close();
            }
            System.out.print("PPT转换成图片 成功！");
            return imgCount;
        }
        catch (Exception e) {
            e.printStackTrace();
            System.out.print("PPT转换成图片 发生异常！");
        }
        return imgCount;
    }



    /**
     * 检查是否为ppt文件
     * @param file
     * @return
     */
    public static boolean checkIsPPTFile(File file) {
        boolean isppt = false;
        String filename = file.getName();
        String suffixname = null;
        if (filename != null && filename.indexOf(".") != -1) {
            suffixname = filename.substring(filename.lastIndexOf("."));
            if (".pptx".equals(suffixname)) {
                isppt = true;
            }
            return isppt;
        } else {
            return isppt;
        }
    }

    /**
     * 创建文件如果路径不存在则创建对应的文件夹
     * @param file
     * @return
     */
    public static File createDirIfNotExist(String file) {
        File fileDir = new File(file);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        return fileDir;
    }

}
